package fm.dongman.animefm.view.fragment
import android.annotation.SuppressLint
import android.app.Activity.RESULT_OK
import android.app.AlertDialog
import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import fm.dongman.animefm.R
import fm.dongman.animefm.view.util.ActivityHelper
import fm.dongman.animefm.view.util.SystemHelper
import fm.dongman.animefm.view.util.ToastHelper
import fm.dongman.animefm.view.widget.EditTextDialog
import kotlinx.android.synthetic.main.item_user_update_myinformation.*
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.os.Build
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.widget.TextView
import com.bumptech.glide.Glide
import fm.dongman.animefm.contractlib.IModel
import fm.dongman.animefm.contractlib.contract.UserEditContract
import fm.dongman.animefm.view.util.CameraGallaryHelper
import fm.dongman.modellib.StaticArea.Injection
import fm.dongman.modellib.model.UserModel
import fm.dongman.presenterlib.presenter.UserEditPresenter
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import fm.dongman.animefm.view.activity.SingleActivity
import fm.dongman.animefm.view.transform.GlideRoundTransform


/**
 * 个人信息设置页面
 * Created by Administrator on 2017/11/20.
 */
class UserEditFragment : BaseFragment(), UserEditContract.IUserEditView, View.OnClickListener {
    private lateinit var mPresenter: UserEditContract.IUserEditPresent
    private var mBitmap: Bitmap? = null
    var user = UserModel()
    lateinit var mDialog:Dialog

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View {
        val view = inflater!!.inflate(R.layout.item_user_update_myinformation, container, false)
        UserEditPresenter(this, Injection.provideUserEditRepository(container!!.context))
        return view
    }

    override fun setPresenter(presenter: UserEditContract.IUserEditPresent) {
        mPresenter = presenter
    }

    override fun initData() {
        mLlUserInfoToolbar.setPadding(0, SystemHelper.getStatusBarHeight(activity), 0, 0)
        mDialog=Dialog(activity,R.style.progress_dialog)
        var view:View=View.inflate(activity,R.layout.layout_loading_dialog,null)
        var text: TextView = view.findViewById(R.id.mTvSaveImgDilog) as TextView
        text.text = "加载中...."
        mDialog.setContentView(view)
    }

    override fun bindData() {
        bindOnClick()     //个人信息页面事件
    }

    /**
     * Activity带参跳转
     */
    @SuppressLint("ObsoleteSdkInt")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            CameraGallaryHelper.CHOOSE_PHOTO -> {
                if (resultCode == RESULT_OK) {
                    if (Build.VERSION.SDK_INT >= 19) {
                        val imagePath=CameraGallaryHelper.handLeImageOnKitkat(data,activity)
                        saveImage(imagePath)
                    } else {
                        val imagePath=CameraGallaryHelper.handleImageBeforeKitKat(data,activity)
                        saveImage(imagePath)
                    }
                }
            }
        }
    }

    /**
     * 保存图片至服务器
     */
    private fun saveImage(imagePath: String?) {
        Glide.with(activity).load(imagePath)
                .bitmapTransform(CenterCrop(activity), GlideRoundTransform(activity, 30))
                .into(mLlUserInfoUpdateAvatarPic)
        mBitmap = CameraGallaryHelper.displayImage(imagePath, activity)
        if(mBitmap!=null){
            mDialog.setTitle("上传中...")
            mDialog.show()
            mPresenter.editPicture(mBitmap!!)
        }
    }

    /**
     * 权限许可
     */
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
        when (requestCode) {
            1 -> if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                openAlbum()  //打开相册
            } else {
                ToastHelper.getInstance(activity).showError("授权失败")
            }
        }
    }


    /**
     * 打开相册
     */
    private fun openAlbum() {
        val intent = Intent("android.intent.action.GET_CONTENT")
        intent.type = "image/*"
        startActivityForResult(intent, CameraGallaryHelper.CHOOSE_PHOTO)
    }


    //页面事件
    override fun onClick(v: View?) {
        when (v!!.id) {

        //返回按钮
            R.id.mUserInfoReturn -> {
                ActivityHelper.backActivity(activity)
            }
        //点击头像
            R.id.mLlUserInfoUpdateAvatar -> {
                if (ContextCompat.checkSelfPermission(activity, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(activity, arrayOf(android.Manifest.permission.WRITE_EXTERNAL_STORAGE), 1)
                } else {
                    openAlbum()
                }
            }
        //姓名
            R.id.mLlUserInfoName -> {
                EditTextDialog.Builder(activity).setTitle("更改用户名")
                        .setOnButtonClickListenr(object : EditTextDialog.Builder.OnButtonClickListener {
                            override fun onCommit(dialog: Dialog, inputContent: String) {
                                if (inputContent == "") {
                                    dialog.dismiss()
                                    ToastHelper.getInstance(activity).showError("不能为空")
                                    return
                                }
                                if (inputContent.length < 5) {
                                    ToastHelper.getInstance(activity).showError("长度不能小于5个字符")
                                    return
                                }
                                if (inputContent.length > 30) {
                                    ToastHelper.getInstance(activity).showError("长度不能超过30个字符")
                                    return
                                }
                                mTvUserInfoName.text = inputContent
                                user.userName = mTvUserInfoName.text.toString()

                                dialog.dismiss()
                            }

                            override fun onCanceled(dialog: Dialog) {
                                dialog.dismiss()
                            }
                        }).build().show()
            }
        //性别
            R.id.mLlUserInfoGender -> {
                val items = arrayOf("男", "女", "保密")
                val dialog = AlertDialog.Builder(activity).setTitle("性别选择").setSingleChoiceItems(items, -1) { dialog, which ->
                            mTvUserInfoGenderText.text = items[which]
                            user.gender = which.toString()
                            dialog.dismiss()
                        }.create()
                dialog.show()
            }
        //签名
            R.id.mLlUserInfoSign -> {
                EditTextDialog.Builder(activity).setTitle("更改签名")
                        .setOnButtonClickListenr(object : EditTextDialog.Builder.OnButtonClickListener {
                            @SuppressLint("ResourceAsColor")
                            override fun onCommit(dialog: Dialog, inputContent: String) {

                                val str: String = inputContent
                                if (str == "") {
                                    ToastHelper.getInstance(activity).showError("不能为空")
                                    dialog.dismiss()
                                    return
                                }
                                if (str.length > 30) {
                                    ToastHelper.getInstance(activity).showError("长度不能超过30个字符")
                                    return
                                }
                                mTvUserInfoSign.text = inputContent
                                user.description = mTvUserInfoSign.text.toString()
                                dialog.dismiss()
                            }

                            override fun onCanceled(dialog: Dialog) {
                                dialog.dismiss()
                            }
                        }).build().show()
            }
        //邮箱

        //手机
            R.id.mLlUserInfoPhone -> {
                ToastHelper.getInstance(activity).showWarn("请进入动漫FM官网修改")
            }
        }
    }

    override fun backResultData() {
        mPresenter.editUserInfo(user) //用户名
        activity.setResult(RESULT_OK)
    }


    //初始化控件
    private fun bindOnClick() {
        mUserInfoReturn.setOnClickListener(this)
        mLlUserInfoUpdateAvatar.setOnClickListener(this)
        mLlUserInfoName.setOnClickListener(this)
        mLlUserInfoGender.setOnClickListener(this)
        mLlUserInfoSign.setOnClickListener(this)
        mLlUserInfoPhone.setOnClickListener(this)
    }

    override fun getViewContext(): Context {
        return activity
    }

    override fun isActive(): Boolean {
        return isAdded
    }

    override fun showNoNetwork() {
        //ToastHelper.getInstance(activity).showError("没有网络！")
    }

    override fun showRefreshFailed() {
        ToastHelper.getInstance(activity).showError(getString(R.string.str_refresh_failed))
    }

    override fun showEditFailed() {
        ToastHelper.getInstance(activity).showError("信息提交失败,重新登录后再试！")
        mDialog.dismiss()
    }

    override fun showEditPictureSuccess(imageUrl: String) {
        mDialog.dismiss()
    }

    override fun showUserInfo(userInfo: IModel.IUserModel) {
        user = userInfo as UserModel
        Glide.with(activity).load(user.avatarUrl)
        .bitmapTransform(CenterCrop(activity),
        GlideRoundTransform(activity,30))
        .into(mLlUserInfoUpdateAvatarPic)
        mTvUserInfoName.text = user.userName

        if (user.gender == "0") {
            mTvUserInfoGenderText.text = "男"
        }
        if (user.gender == "1") {
            mTvUserInfoGenderText.text = "女"
        }
        if (user.gender == "2") {
            mTvUserInfoGenderText.text = "保密"
        }

        mTvUserInfoSign.text = user.description
    }


    override fun onStart() {
        super.onStart()
        if (user == null || mBitmap == null) {
            mPresenter.startLoad()
        }
    }


    companion object {
        fun getInstance(): UserEditFragment {
            return UserEditFragment()
        }
    }
}